<template>
  <a-spin v-if="captching" class="img-captcha"></a-spin>
  <div v-else-if="src" @click.stop="refreshCaptcha">
    <img
      class="img-captcha"
      :src="src"
      alt="点击刷新"
      title="点击刷新">
    <!-- <span class="tip-captcha">点击，换一个</span> -->
  </div>
</template>
<script>
import { defineComponent, ref } from 'vue'
import { BASE_URL, PREFIX } from '../../api/config'
import { getFingerPrint } from '@wattjs/network'
import { ll } from '../../utils'

export default defineComponent({
  props: {
    scene: {
      type: String,
      default: 'login'
    }
  },
  setup (props) {
    const clientId = ref(ll.get('CLIENT-ID') || '')
    const captching = ref(false)
    const src = ref('')

    const refreshCaptcha = () => {
      captching.value = true
      src.value = `${BASE_URL}${PREFIX}/common/refreshCaptcha?scene=${props.scene}&deviceId=${clientId.value}&_=${Date.now()}`
      captching.value = false
    }

    // 初始化
    if (!ll.get('CLIENT-ID')) {
      getFingerPrint().then(deviceId => {
        ll.set('CLIENT-ID', deviceId)
        clientId.value = deviceId
        clientId.value && refreshCaptcha()
      }).catch(() => {})
    } else {
      refreshCaptcha()
    }

    return {
      captching,
      src,
      refreshCaptcha
    }
  }
})
</script>
<style lang="less" scoped>
.img-captcha {
  height: 40px;
  cursor: pointer;
}
.tip-captcha {
  font-size: 12px;
  color: #999;
  display: inline-block;
}
</style>
